<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 用户信息 - 模拟从localStorage获取
const currentUser = computed(() => {
  const user = localStorage.getItem('currentUser')
  return user ? JSON.parse(user) : {
    id: '1',
    name: 'jinjin',
    avatar: 'https://picsum.photos/id/64/200/200',
    status: 'online'
  }
})

// 聊天消息列表
const messages = ref([
  {
    id: '1',
    sender: 'system',
    content: '欢迎来到ChatWave！这是一个现代化的聊天应用。',
    timestamp: new Date().toISOString(),
    isCurrentUser: false
  },
  {
    id: '2',
    sender: {
      id: '2',
      name: '李明',
      avatar: 'https://picsum.photos/id/91/200/200'
    },
    content: '你好！很高兴见到你！',
    timestamp: new Date(Date.now() - 3600000).toISOString(),
    isCurrentUser: false
  },
  {
    id: '3',
    sender: currentUser.value,
    content: '你好李明，我是jinjin！',
    timestamp: new Date(Date.now() - 3000000).toISOString(),
    isCurrentUser: true
  }
])

// 聊天列表
const conversations = ref([
  {
    id: '1',
    name: '李明',
    avatar: 'https://picsum.photos/id/91/200/200',
    lastMessage: '你好！很高兴见到你！',
    timestamp: new Date(Date.now() - 3600000).toISOString(),
    unread: 1,
    status: 'online'
  },
  {
    id: '2',
    name: '张华',
    avatar: 'https://picsum.photos/id/26/200/200',
    lastMessage: '项目进展怎么样了？',
    timestamp: new Date(Date.now() - 86400000).toISOString(),
    unread: 0,
    status: 'offline'
  },
  {
    id: '3',
    name: '赵芳',
    avatar: 'https://picsum.photos/id/65/200/200',
    lastMessage: '明天一起吃午饭吗？',
    timestamp: new Date(Date.now() - 172800000).toISOString(),
    unread: 0,
    status: 'busy'
  }
])

// 当前选中的会话
const selectedConversation = ref(conversations.value[0])

// 输入的消息内容
const messageInput = ref('')

// 侧边栏状态
const sidebarOpen = ref(true)

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now - date
  
  if (diff < 60000) { // 小于1分钟
    return '刚刚'
  } else if (diff < 3600000) { // 小于1小时
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) { // 小于1天
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  } else {
    return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' })
  }
}

// 发送消息
const sendMessage = () => {
  if (!messageInput.value.trim()) return
  
  const newMessage = {
    id: Date.now().toString(),
    sender: currentUser.value,
    content: messageInput.value.trim(),
    timestamp: new Date().toISOString(),
    isCurrentUser: true
  }
  
  messages.value.push(newMessage)
  messageInput.value = ''
  
  // 模拟对方回复
  setTimeout(() => {
    const replies = [
      '好的，明白了！',
      '收到，我会处理的。',
      '哈哈哈，太有趣了！',
      '嗯，这个想法不错！',
      '稍后我再回复你。'
    ]
    const randomReply = replies[Math.floor(Math.random() * replies.length)]
    
    messages.value.push({
      id: (Date.now() + 1).toString(),
      sender: selectedConversation.value,
      content: randomReply,
      timestamp: new Date().toISOString(),
      isCurrentUser: false
    })
  }, 1000)
  
  // 更新会话列表的最后消息
  selectedConversation.value.lastMessage = newMessage.content
  selectedConversation.value.timestamp = newMessage.timestamp
  selectedConversation.value.unread = 0
  
  // 滚动到底部
  nextTick(() => {
    const chatContainer = document.querySelector('.chat-messages')
    if (chatContainer) {
      chatContainer.scrollTop = chatContainer.scrollHeight
    }
  })
}

// 切换会话
const selectConversation = (conversation) => {
  selectedConversation.value = conversation
  selectedConversation.value.unread = 0
  
  // 在实际应用中，这里应该加载对应会话的消息
  // 这里为了演示，我们只模拟几条消息
  if (conversation.id !== '1') {
    messages.value = [
      {
        id: '1',
        sender: 'system',
        content: `你正在与${conversation.name}聊天。`,
        timestamp: new Date().toISOString(),
        isCurrentUser: false
      }
    ]
  }
}

// 切换侧边栏
const toggleSidebar = () => {
  sidebarOpen.value = !sidebarOpen.value
}

// 退出登录
const logout = () => {
  localStorage.removeItem('currentUser')
  router.push('/login')
}

// 组件挂载后滚动到底部
const nextTick = (callback) => {
  setTimeout(callback, 0)
}

onMounted(() => {
  nextTick(() => {
    const chatContainer = document.querySelector('.chat-messages')
    if (chatContainer) {
      chatContainer.scrollTop = chatContainer.scrollHeight
    }
  })
})
</script>

<template>
  <div class="chat-app">
    <!-- 顶部导航 -->
    <header class="chat-header">
      <div class="header-left">
        <button class="sidebar-toggle" @click="toggleSidebar">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <line x1="3" y1="12" x2="21" y2="12"></line>
            <line x1="3" y1="6" x2="21" y2="6"></line>
            <line x1="3" y1="18" x2="21" y2="18"></line>
          </svg>
        </button>
        <h1 class="app-title">ChatWave</h1>
      </div>
      <div class="header-right">
        <button class="logout-button" @click="logout">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path>
            <polyline points="16 17 21 12 16 7"></polyline>
            <line x1="21" y1="12" x2="9" y2="12"></line>
          </svg>
          退出
        </button>
      </div>
    </header>

    <div class="chat-main">
      <!-- 侧边栏 -->
      <aside class="chat-sidebar" :class="{ 'sidebar-closed': !sidebarOpen }">
        <!-- 搜索框 -->
        <div class="search-container">
          <div class="search-input-wrapper">
            <svg class="search-icon" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#94a3b8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <circle cx="11" cy="11" r="8"></circle>
              <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
            </svg>
            <input type="text" placeholder="搜索聊天..." class="search-input">
          </div>
        </div>

        <!-- 会话列表 -->
        <div class="conversations-list">
          <div 
            v-for="conversation in conversations" 
            :key="conversation.id" 
            class="conversation-item" 
            :class="{ 'active': selectedConversation.id === conversation.id }"
            @click="selectConversation(conversation)"
          >
            <div class="conversation-avatar">
              <img :src="conversation.avatar" :alt="conversation.name">
              <div class="status-indicator" :class="conversation.status"></div>
            </div>
            <div class="conversation-info">
              <div class="conversation-header">
                <h3 class="conversation-name">{{ conversation.name }}</h3>
                <span class="conversation-time">{{ formatTime(conversation.timestamp) }}</span>
              </div>
              <p class="conversation-last-message">{{ conversation.lastMessage }}</p>
            </div>
            <div v-if="conversation.unread > 0" class="unread-badge">{{ conversation.unread }}</div>
          </div>
        </div>
      </aside>

      <!-- 聊天区域 -->
      <main class="chat-content">
        <!-- 聊天头部 -->
        <div class="chat-header-info">
          <div class="chat-partner-info">
            <div class="partner-avatar">
              <img :src="selectedConversation.avatar" :alt="selectedConversation.name">
              <div class="status-indicator" :class="selectedConversation.status"></div>
            </div>
            <div class="partner-details">
              <h2 class="partner-name">{{ selectedConversation.name }}</h2>
              <span class="partner-status">
                {{ selectedConversation.status === 'online' ? '在线' : 
                   selectedConversation.status === 'busy' ? '忙碌' : '离线' }}
              </span>
            </div>
          </div>
          <div class="chat-actions">
            <button class="action-button">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="M15.05 11H3a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2.05a.5.5 0 0 0-.5.5v1a.5.5 0 0 0 .5.5H21a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2h-6.95a.5.5 0 0 0-.5.5v1a.5.5 0 0 0 .5.5H19a2 2 0 0 1 2 2v1a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-4a2 2 0 0 1 2-2h2.05a.5.5 0 0 0 .5-.5v-1a.5.5 0 0 0-.5-.5Z"></path>
              </svg>
            </button>
            <button class="action-button">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <rect x="2" y="3" width="20" height="14" rx="2" ry="2"></rect>
                <line x1="8" y1="21" x2="16" y2="21"></line>
                <line x1="12" y1="17" x2="12" y2="21"></line>
              </svg>
            </button>
          </div>
        </div>

        <!-- 消息区域 -->
        <div class="chat-messages">
          <div v-for="message in messages" :key="message.id" class="message-wrapper" :class="{ 'message-self': message.isCurrentUser }">
            <div v-if="!message.isCurrentUser" class="message-avatar">
              <img :src="message.sender.avatar || 'https://picsum.photos/id/237/200/200'" :alt="message.sender.name">
            </div>
            <div class="message-content" :class="{ 'message-self-content': message.isCurrentUser }">
              <p class="message-text">{{ message.content }}</p>
              <span class="message-time">{{ formatTime(message.timestamp) }}</span>
            </div>
            <div v-if="message.isCurrentUser" class="message-avatar">
              <img :src="currentUser.avatar" :alt="currentUser.name">
            </div>
          </div>
        </div>

        <!-- 消息输入区域 -->
        <div class="message-input-container">
          <div class="input-tools">
            <button class="tool-button">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"></path>
                <polyline points="14 2 14 8 20 8"></polyline>
                <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path>
                <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path>
              </svg>
            </button>
            <button class="tool-button">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"></path>
                <polyline points="14 2 14 8 20 8"></polyline>
              </svg>
            </button>
            <button class="tool-button">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <circle cx="12" cy="12" r="10"></circle>
                <polyline points="14.31 8 20.05 17.94"></polyline>
                <line x1="9.69" y1="8" x2="21.17" y2="8"></line>
                <polyline points="7.38 12" x2="13.12" y2="2.06"></polyline>
                <line x1="9.69" y1="16" x2="3.95" y2="6.06"></line>
                <line x1="14.31" y1="16" x2="2.83" y2="16"></line>
                <polyline points="16.62" x2="10.88" y2="21.94"></polyline>
              </svg>
            </button>
          </div>
          <div class="input-wrapper">
            <input 
              type="text" 
              v-model="messageInput" 
              placeholder="输入消息..." 
              class="message-input"
              @keypress.enter="sendMessage"
            >
            <button class="send-button" @click="sendMessage">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <line x1="22" y1="2" x2="11" y2="13"></line>
                <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
              </svg>
            </button>
          </div>
        </div>
      </main>
    </div>
  </div>
</template>

<style scoped>
/* 聊天应用容器 */
.chat-app {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f8fafc;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  overflow: hidden;
}

/* 顶部导航 */
.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 64px;
  background: white;
  border-bottom: 1px solid #e2e8f0;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.sidebar-toggle {
  background: none;
  border: none;
  cursor: pointer;
  color: #64748b;
  padding: 8px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.sidebar-toggle:hover {
  background-color: #f1f5f9;
  color: #3b82f6;
}

.app-title {
  font-size: 20px;
  font-weight: 700;
  color: #1e293b;
  margin: 0;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logout-button {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  background: #f1f5f9;
  border: none;
  border-radius: 8px;
  color: #64748b;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.logout-button:hover {
  background: #e2e8f0;
  color: #ef4444;
}

/* 主要内容区域 */
.chat-main {
  flex: 1;
  display: flex;
  overflow: hidden;
}

/* 侧边栏 */
.chat-sidebar {
  width: 320px;
  background: white;
  border-right: 1px solid #e2e8f0;
  display: flex;
  flex-direction: column;
  transition: width 0.3s ease;
}

.sidebar-closed {
  width: 0;
  overflow: hidden;
}

/* 搜索框 */
.search-container {
  padding: 16px;
  border-bottom: 1px solid #e2e8f0;
}

.search-input-wrapper {
  display: flex;
  align-items: center;
  background: #f1f5f9;
  border-radius: 12px;
  padding: 0 12px;
}

.search-icon {
  flex-shrink: 0;
}

.search-input {
  flex: 1;
  padding: 10px 12px;
  border: none;
  background: transparent;
  outline: none;
  font-size: 14px;
  color: #1e293b;
}

.search-input::placeholder {
  color: #94a3b8;
}

/* 会话列表 */
.conversations-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px 0;
}

.conversation-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  transition: background-color 0.3s ease;
  position: relative;
}

.conversation-item:hover {
  background-color: #f1f5f9;
}

.conversation-item.active {
  background-color: #dbeafe;
}

.conversation-avatar {
  position: relative;
  margin-right: 12px;
}

.conversation-avatar img {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
}

.status-indicator {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  border: 2px solid white;
}

.status-indicator.online {
  background-color: #10b981;
}

.status-indicator.offline {
  background-color: #94a3b8;
}

.status-indicator.busy {
  background-color: #f59e0b;
}

.conversation-info {
  flex: 1;
  min-width: 0;
}

.conversation-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.conversation-name {
  font-size: 15px;
  font-weight: 600;
  color: #1e293b;
  margin: 0;
}

.conversation-time {
  font-size: 12px;
  color: #94a3b8;
}

.conversation-last-message {
  font-size: 14px;
  color: #64748b;
  margin: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.unread-badge {
  background-color: #3b82f6;
  color: white;
  font-size: 12px;
  font-weight: 600;
  padding: 2px 8px;
  border-radius: 12px;
  min-width: 20px;
  text-align: center;
}

/* 聊天内容区域 */
.chat-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #f8fafc;
}

/* 聊天头部信息 */
.chat-header-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: white;
  border-bottom: 1px solid #e2e8f0;
}

.chat-partner-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.partner-avatar {
  position: relative;
}

.partner-avatar img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.partner-details h2 {
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
  margin: 0 0 2px 0;
}

.partner-status {
  font-size: 12px;
  color: #64748b;
}

.chat-actions {
  display: flex;
  gap: 8px;
}

.action-button {
  background: none;
  border: none;
  color: #64748b;
  cursor: pointer;
  padding: 8px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.action-button:hover {
  background-color: #f1f5f9;
  color: #3b82f6;
}

/* 消息区域 */
.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.message-wrapper {
  display: flex;
  align-items: flex-end;
  gap: 8px;
}

.message-wrapper.message-self {
  flex-direction: row-reverse;
}

.message-avatar img {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  object-fit: cover;
}

.message-content {
  max-width: 60%;
  background: white;
  padding: 12px 16px;
  border-radius: 18px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  position: relative;
}

.message-self-content {
  background: #3b82f6;
  color: white;
}

.message-text {
  margin: 0 0 4px 0;
  font-size: 15px;
  line-height: 1.4;
  word-wrap: break-word;
}

.message-time {
  font-size: 12px;
  color: #94a3b8;
  display: block;
  text-align: right;
}

.message-self-content .message-time {
  color: rgba(255, 255, 255, 0.7);
}

/* 消息输入区域 */
.message-input-container {
  padding: 16px 24px;
  background: white;
  border-top: 1px solid #e2e8f0;
}

.input-tools {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
}

.tool-button {
  background: none;
  border: none;
  color: #64748b;
  cursor: pointer;
  padding: 8px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.tool-button:hover {
  background-color: #f1f5f9;
  color: #3b82f6;
}

.input-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  background: #f1f5f9;
  border-radius: 24px;
  padding: 4px;
}

.message-input {
  flex: 1;
  padding: 12px 16px;
  border: none;
  background: transparent;
  outline: none;
  font-size: 15px;
  color: #1e293b;
  resize: none;
}

.message-input::placeholder {
  color: #94a3b8;
}

.send-button {
  background: #3b82f6;
  border: none;
  color: white;
  cursor: pointer;
  padding: 10px 16px;
  border-radius: 20px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.send-button:hover {
  background: #2563eb;
  transform: scale(1.05);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-sidebar {
    width: 280px;
  }
  
  .message-content {
    max-width: 75%;
  }
}

@media (max-width: 480px) {
  .chat-sidebar {
    position: absolute;
    left: 0;
    top: 64px;
    bottom: 0;
    z-index: 5;
    box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
  }
  
  .sidebar-closed {
    left: -280px;
  }
  
  .app-title {
    display: none;
  }
  
  .chat-header {
    padding: 0 12px;
  }
  
  .chat-messages {
    padding: 16px;
  }
  
  .message-input-container {
    padding: 12px 16px;
  }
}

/* 滚动条样式 */
.conversations-list::-webkit-scrollbar,
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.conversations-list::-webkit-scrollbar-track,
.chat-messages::-webkit-scrollbar-track {
  background: #f1f5f9;
}

.conversations-list::-webkit-scrollbar-thumb,
.chat-messages::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 3px;
}

.conversations-list::-webkit-scrollbar-thumb:hover,
.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}
</style>